package com.smartlazy.delay.queue.client.timer;

import com.alibaba.fastjson.JSONObject;
import com.github.youzan.httpfetch.HttpApiConfiguration;
import com.github.youzan.httpfetch.HttpApiService;
import com.smartlazy.delay.queue.client.api.DelayQueueApi;
import com.smartlazy.delay.queue.client.bean.JobItem;
import com.smartlazy.delay.queue.client.bean.ReturnInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 *
 * @author howe
 */
@Slf4j
public class TickHandler implements Runnable {
    private String tickName;

    public TickHandler(String tickName) {
        this.tickName = tickName;
    }

    @Override
    public void run() {
        log.info(tickName + " is running");
        try {
            HttpApiService httpApiService = new HttpApiService(new HttpApiConfiguration());
            httpApiService.init();
            DelayQueueApi delayQueueApi = httpApiService.getOrCreateService(DelayQueueApi.class);
            ReturnInfo<JobItem> responseVo = delayQueueApi.pop("订单延时");
            log.info("消费者定时取得任务 :" + JSONObject.toJSONString(responseVo));
            if (responseVo.getData() != null && !StringUtils.isEmpty(responseVo.getData().getId())) {
                JobItem param = new JobItem();
                param.setId(responseVo.getData().getId());
                ReturnInfo<Boolean> deleteResponseVo = delayQueueApi.delete(param);
                log.info("消费者延时处理成功 " + deleteResponseVo.getData());
            }
        } catch (Exception e) {
            log.error("时钟执行失败 " + tickName, e);
        }
    }
}
